<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Role;
use app\common\model\Room as modelRoom;
use app\common\model\RoomPeople;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

class Room extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ["*"];

    public function __construct(Request $requests = null)
    {
        $request = input();
        if (isset($request['roomNumber']) && !empty($request['roomNumber'])) {
            $roomId         = numberDecode($request['roomNumber']);
            $this->roomInfo = modelRoom::get($roomId);
        }
        parent::__construct($requests);
    }

    /** 加入房间 */
    public function joinRoom()
    {
        $param = $this->request->param();
        $this->validateCommon('Room.joinRoom', $this->serial_number);
        if (!$this->roomInfo) $this->error('房间不存在');
        if ($param['password'] != $this->roomInfo->password) $this->error('房间口令错误');
        if ($this->roomInfo->is_over == 2) $this->error('游戏已结束');
        if ($this->roomInfo->onlien_num >= $this->roomInfo->total_num) $this->error('房间人数已满');
        $roomData = [
            'room_id' => $this->roomInfo->id,
            'user_id' => $this->auth->id,
        ];
        $isJoin   = RoomPeople::where(['room_id' => $this->roomInfo->id, 'user_id' => $this->auth->id])->find();
        if ($isJoin) $this->error('您已加入该房间,请勿重复加入');
        $isOtherJoin = RoomPeople::where(['user_id'=>$this->auth->id,'status'=>1])->find();
        if($isOtherJoin) $this->error('您已参加游戏,请勿在角色死亡前加入别的房间');
        $result = false;
        Db::startTrans();
        try {
            RoomPeople::create($roomData);
            $result = modelRoom::where('id', $this->roomInfo->id)->setInc('onlien_num');
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('加入房间失败'));
        }
        $this->success('加入房间成功');
    }

    /** 房间人员 */
    public function roomPeople()
    {
        $param = $this->request->param();
        $this->validateCommon('Room.roomPeople', $this->serial_number);
        $list = Db::name('room_people')->where(['room_id' => $this->roomInfo->id])
                          ->group('user_id')
                          ->field('id,role_id roleId,role_name roleName,status,createtime,user_id userId')
                          ->order('createtime')
                          ->paginate($param['pageCount'], false, ['page' => $param['page']])->each(function ($item) {
                $item['roleName']           = Role::where('id', $item['roleId'])->value('role_name') ?? "未分配";
                $item['userInfo']           = \app\common\model\User::where('id', $item['userId'])->field('username userName,avatar,number userNumber')->find();
                $item['userInfo']['avatar'] = getCurrentUrl($item['userInfo']['avatar']);
                return getNullSet($item);
            });
        $this->success('人员列表', $list);
    }

    /** 获取游戏结果 */
    public function geamResult()
    {
        $param = $this->request->param();
        $this->validateCommon('Room.geamResult', $this->serial_number);
        $roomId = numberDecode($param['roomNumber']);
        $geamInfo =  RoomPeople::where(['room_id'=>$roomId,'user_id'=>$this->auth->id])->find();
        $roomInfo = modelRoom::get($roomId);
        if(!$roomInfo) $this->error('房间信息不存在');
        if($roomInfo->is_over != 2) $this->error('游戏未结束');
        if(!$geamInfo) $this->error('房间信息不存在');
        $this->success('游戏结果',['result'=>$geamInfo['is_win'],'score'=>120]);
    }

    /** 自己角色 */
    public function selfRole()
    {
        $param = $this->request->param();
        $this->validateCommon('Room.selfRole', $this->serial_number);
        $roomId = numberDecode($param['roomNumber']);
        $roleId =  RoomPeople::where(['room_id'=>$roomId,'user_id'=>$this->auth->id])->value('role_id');
        if(empty($roleId)) $this->error('暂未找到您的角色,请联系主持人分配');
        $this->success('角色ID',$roleId);
    }

    /** 角色详情 */
    public function roleDetail()
    {
        $param = $this->request->param();
        $this->validateCommon('Room.roleDetail', $this->serial_number);
        $roleDetail = Role::get($param['roleId']);
        if(empty($roleDetail)) $this->error('角色不存在');
        $roleDetail->image = getCurrentUrl($roleDetail->image);
        $this->success('角色详情', $roleDetail);
    }

    /** 角色列表 */
    public function roleList()
    {
        $param = $this->request->param();
        $this->validateCommon('Room.roleList', $this->serial_number);
        $roomId = numberDecode($param['roomNumber']);
        $roleIds = RoomPeople::where('id',$roomId)->value('role_ids');
        $item = Role::whereIn('id',$roleIds)->paginate($param['pageCount'],false,['page'=>$param['page']])
                    ->each(function ($item){
                        $item['image'] = getCurrentUrl($item['image']);
                    });
        $this->success('角色列表', $item);
    }

}